<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">

          <el-form-item label="开始时间">
            <el-date-picker clearable v-model="queryParams.startDate" type="date" value-format="YYYY-MM-DD 00:00:00"
              placeholder="请选择开始时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="结束时间">
            <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="YYYY-MM-DD 23:59:59"
              placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
          <!--       <el-form-item label="会员卡编号" prop="cardId">
            <el-input v-model="queryParams.cardId" placeholder="请输入会员卡编号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--        <el-form-item label="选择会员卡" prop="cardId">
            <el-select v-model="queryParams.cardId" placeholder="请选择" filterable clearable>
              <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName"
                :value="dict.id"></el-option>
            </el-select>
          </el-form-item> -->
          <!--         <el-form-item label="选择会员" prop="memberId">
            <el-select v-model="queryParams.memberId" placeholder="请选择" filterable clearable>
              <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName"
                :value="dict.id"></el-option>
            </el-select>
          </el-form-item> -->
          <!--        <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单数量" prop="orderNum">
            <el-input v-model="queryParams.orderNum" placeholder="请输入订单数量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="订单价格" prop="orderPrice">
            <el-input v-model="queryParams.orderPrice" placeholder="请输入订单价格" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
            <el-input v-model="queryParams.thirdPartyOrderNo" placeholder="请输入三方订单编号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付金额" prop="amount">
            <el-input v-model="queryParams.amount" placeholder="请输入支付金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付时间" prop="payTime">
            <el-date-picker clearable
              v-model="queryParams.payTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择支付时间"
            />
          </el-form-item> -->
          <!--          <el-form-item label="有效期至" prop="indateTime">
            <el-date-picker clearable
              v-model="queryParams.indateTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期至"
            />
          </el-form-item> -->
          <!--          <el-form-item label="办卡日期" prop="registerCardTime">
            <el-date-picker clearable
              v-model="queryParams.registerCardTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择办卡日期"
            />
          </el-form-item> -->
          <!--          <el-form-item label="销售人，人员信息的主键id" prop="gymUserId">
            <el-input v-model="queryParams.gymUserId" placeholder="请输入销售人，人员信息的主键id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!--          <el-form-item label="支付方式" prop="patternPayment">
            <el-input v-model="queryParams.patternPayment" placeholder="请输入支付方式" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
<!--       <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
           <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:order:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <span style="font-weight: bold;">当前总金额:{{financeInfo.priceTotal || 0}}元</span>
        <span style="margin-left: 88px;margin-right: 88px;font-weight: bold;">当前总订单数量:{{financeInfo.count || 0}}</span>
        <span style="margin-right: 88px;font-weight: bold;">当前退款数量:{{financeInfo.refundCount || 0}}</span>
        <span style="font-weight: bold;">当前退款总金额:{{financeInfo.refundPriceTotal || 0}}元</span>
      </template>

      <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="订单id" align="center" prop="id" v-if="true" />
        <el-table-column label="健身房id" align="center" prop="gymId" /> -->
        <el-table-column label="会员姓名" align="center">
          <template #default="scope">
            <span>{{scope.row.memberName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员卡名称" align="center">
          <template #default="scope">
            <span>{{scope.row.cardName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="销售类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_market_type" :value="scope.row.marketType" />
          </template>
        </el-table-column>
        <el-table-column label="会员卡类型" align="center">
          <template #default="scope">
            <dict-tag :options="g_finance_type" :value="scope.row.memberCourseType" />
          </template>
        </el-table-column>
<!--        <el-table-column label="办卡日期" align="center">
          <template #default="scope">
            <span>{{scope.row.orderVo.registerCardTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单数量" align="center">
          <template #default="scope">
            <span>{{scope.row.orderVo.orderNum}}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="订单价格" align="center">
          <template #default="scope">
            <span>{{scope.row.orderPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付金额" align="center">
          <template #default="scope">
            <span>{{scope.row.amount}}</span>
          </template>
        </el-table-column>

        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" align="center">
          <template #default="scope">
            <dict-tag :options="orderstats" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
<!--        <el-table-column label="退款金额" align="center">
          <template #default="scope">
            <span>{{scope.row.refundAmount}}</span>
          </template>
        </el-table-column> -->
        <!--        <el-table-column label="办卡日期" align="center" prop="registerCardTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerCardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="销售人" align="center">
          <template #default="scope">
            <span>{{scope.row.nickName}}</span>
          </template>
        </el-table-column>


        <el-table-column label="支付方式" align="center">
          <template #default="scope">
            <dict-tag :options="g_pay_type" :value="scope.row.patternPayment" />
          </template>
        </el-table-column>

        <!--     <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
          <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:order:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:order:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="560px" append-to-body>
      <el-form ref="orderFormRef" :model="form" :rules="rules" label-width="110px">
        <!--    <el-form-item label="健身房id" prop="gymId">
          <el-input v-model="form.gymId" placeholder="请输入健身房id" type="number" :min="0" />
        </el-form-item> -->
        <!--      <el-form-item label="会员卡编号" prop="cardId">
          <el-input v-model="form.cardId" placeholder="请输入会员卡编号" />
        </el-form-item> -->
        <el-form-item label="选择会员卡" prop="cardId">

          <el-select v-model="form.cardId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择会员" prop="memberId">

          <el-select v-model="form.memberId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in memberList" :key="dict.id" :label="dict.memberName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <!--       <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item> -->
        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入订单数量" type="number" :min="0" />
        </el-form-item>
        <!--        <el-form-item label="订单价格" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单价格(元)" type="number" :min="0" />
        </el-form-item> -->
        <!--       <el-form-item label="三方订单编号" prop="thirdPartyOrderNo">
          <el-input v-model="form.thirdPartyOrderNo" placeholder="请输入三方订单编号" />
        </el-form-item> -->
        <el-form-item label="支付金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入支付金额" type="number" :min="0" />
        </el-form-item>
        <!--        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="有效期至" prop="indateTime">
          <el-date-picker clearable v-model="form.indateTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期至">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="办卡日期" prop="registerCardTime">
          <el-date-picker clearable v-model="form.registerCardTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择办卡日期">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="销售人id" prop="gymUserId">
          <el-input v-model="form.gymUserId" placeholder="请输入销售人，人员信息的主键id" />
        </el-form-item> -->
        <el-form-item label="跟进教练" prop="userId">
          <span>{{form.userId}}</span>
          <el-select v-model="form.userId" placeholder="请选择" :disabled='dialog.isdis' filterable clearable>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售类型" prop="marketType">
          <el-select v-model="form.marketType" placeholder="请选择">
            <el-option v-for="item in g_market_type" :key="item.value" :label="item.label"
              :value="item.value.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择">
            <el-option v-for="dict in g_order_type" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式" prop="patternPayment">
          <el-select v-model="form.patternPayment" placeholder="请选择">
            <el-option v-for="dict in g_pay_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order" lang="ts">
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, reportFormsOrder } from '@/api/primary/order';
  import { listClubCard } from '@/api/primary/clubCard';
  import { ClubCardForm } from '@/api/primary/clubCard/types';
  import { listMember } from '@/api/primary/member';
  import { OrderVO, OrderQuery, OrderForm } from '@/api/primary/order/types';
  import { listRole } from "@/api/system/role";
  import { listCoach } from '@/api/primary/coach';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { orderstats, g_pay_type, g_market_type, g_finance_type } = toRefs<any>(proxy?.useDict("orderstats", "g_pay_type", "g_market_type", "g_finance_type"));
  const memberList = ref<any>([]);
  let clubCardLista = ref<any>([]);
  const coachList = ref<any>([]);
  const roleCan = ref<any>();
  const value2 = ref<any>();
  const roleList = ref<any>();
  const orderList = ref<OrderVO[]>([]);
  const financeInfo = ref<any>(
  {
    decimal:'无数据',
    refundPriceTotal:undefined,
    refundCount:undefined,
    count:undefined
  });
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref<ElFormInstance>();
  const orderFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: '',
    isdis: 0
  });
  const initFormData : OrderForm = {
    id: undefined,
    gymId: undefined,
    memberType: undefined,
    userId: undefined,
    memberId: undefined,
    cardId: undefined,
    orderNo: undefined,
    orderNum: undefined,
    orderPrice: undefined,
    thirdPartyOrderNo: undefined,
    amount: undefined,
    payTime: undefined,
    indateTime: undefined,
    orderStatus: undefined,
    registerCardTime: undefined,
    gymUserId: undefined,
    marketType: undefined,
    patternPayment: undefined,
    startDate: undefined,
    endDate: undefined
  }
  const data = reactive<PageData<OrderForm, OrderQuery>>({
    form: { ...initFormData },
    queryParams: {
      startDate: undefined,
      endDate: undefined,
      pageNum: 1,
      pageSize: 10,
      memberType: undefined,
      memberId: undefined,
      gymId: undefined,
      userId: undefined,
      cardId: undefined,
      orderNo: undefined,
      orderNum: undefined,
      orderPrice: undefined,
      thirdPartyOrderNo: undefined,
      amount: undefined,
      payTime: undefined,
      indateTime: undefined,
      orderStatus: undefined,
      registerCardTime: undefined,
      gymUserId: undefined,
      marketType: undefined,
      patternPayment: undefined,
      params: {
      }
    },
    rules: {
      // id: [
      //   { required: true, message: "订单id不能为空", trigger: "change" }
      // ],
      userId: [
        { required: true, message: "跟进教练不能为空", trigger: "change" }
      ],
      cardId: [
        { required: true, message: "会员卡编号不能为空", trigger: "change" }
      ],
      orderNo: [
        { required: true, message: "订单编号不能为空", trigger: "change" }
      ],
      orderNum: [
        { required: true, message: "订单数量不能为空", trigger: "change" }
      ],
      orderPrice: [
        { required: true, message: "订单价格不能为空", trigger: "change" }
      ],
      // thirdPartyOrderNo: [
      //   { required: true, message: "三方订单编号不能为空", trigger: "change" }
      // ],
      amount: [
        { required: true, message: "支付金额不能为空", trigger: "change" }
      ],
      payTime: [
        { required: true, message: "支付时间不能为空", trigger: "change" }
      ],
      indateTime: [
        { required: true, message: "有效期至不能为空", trigger: "blur" }
      ],
      orderStatus: [
        { required: true, message: "订单状态不能为空", trigger: "change" }
      ],
      registerCardTime: [
        { required: true, message: "办卡日期不能为空", trigger: "blur" }
      ],
      gymUserId: [
        { required: true, message: "销售人不能为空", trigger: "change" }
      ],
      marketType: [
        { required: true, message: "销售类型不能为空", trigger: "change" }
      ],
      patternPayment: [
        { required: true, message: "支付方式", trigger: "change" }
      ]
    }
  });
  const { queryParams, form, rules } = toRefs(data);
  /** 查询会员卡信息列表 */
  const getListcard = async () => {
    const res = await listClubCard(queryParams.value);
    clubCardLista = res.rows;
    console.log(clubCardLista, '会员卡列表')
  }

  /** 查询会员信息列表 */
  const getListvip = async () => {
    queryParams.value.memberType = 0
    const res = await listMember(queryParams.value);
    memberList.value = res.rows;
    console.log(memberList.value, '正式会员表')
    queryParams.value.memberType = undefined
  }
  // 教练表
  const getListb = async () => {
    const res = await listCoach(queryParams.value);
    coachList.value = res.rows;
    console.log(coachList.value, '教练信息表')
  }

  /** 查询订单信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await reportFormsOrder(queryParams.value);
    orderList.value = res.data.orderVoList;
    financeInfo.value = res.data
    total.value = financeInfo.value.count
    console.log(financeInfo.value.refundPriceTotal, 'aaaaaaaaaaaaaaaaaaaaaaa')
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    orderFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : OrderVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.isdis = false
    dialog.visible = true;
    dialog.title = "添加订单信息";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: OrderVO) => {
    reset();
    dialog.isdis = true
    const _id = row?.id || ids.value[0]
    const res = await getOrder(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改订单信息";
  }

  /** 提交按钮 */
  const submitForm = () => {
    orderFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateOrder(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addOrder(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("添加成功");
          queryParams.value.cardId = ''
          queryParams.value.memberId = ''
        }

        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: OrderVO) => {
    const _ids = row?.id || ids.value;
    let name = row.cardId
    await proxy?.$modal.confirm('是否确认删除订单信息编号为"' + name + '"的数据项？').finally(() => loading.value = false);
    await delOrder(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/order/export', {
      ...queryParams.value
    }, `order_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    // 获取当前日期
    const currentDate = new Date();
    // 获取当前日期的星期几（0 表示周日，1 表示周一，以此类推）
    let currentDayOfWeek = currentDate.getDay();
    // 将星期日的索引（0）转换为 7，以便于后续计算
    if (currentDayOfWeek === 0) {
      currentDayOfWeek = 7;
    }
    // 计算最近一周的开始日期
    const startOfWeek = new Date(currentDate);
    startOfWeek.setDate(currentDate.getDate() - currentDayOfWeek + 1); // 从本周的星期一开始
    // 计算最近一周的结束日期
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    // 将日期格式转换为 ISO 8601 格式的字符串
    const startISOString = startOfWeek.toISOString();
    const endISOString = endOfWeek.toISOString();
    // 提取日期部分，忽略时间部分
    const start = startISOString.split('T')[0];
    const end = endISOString.split('T')[0];
    // 将日期格式从 yyyy-mm-dd 转换为 yyyy-mm-dd 00:00:00
    let formattedStartDate = start + ' 00:00:00';
    let formattedEndDate = end + ' 23:59:59';
    queryParams.value.startDate = formattedStartDate
    queryParams.value.endDate = formattedEndDate
    console.log("最近一周的开始日期是aa：" + queryParams.value.startDate);
    console.log("最近一周的结束日期是bb：" + queryParams.value.endDate);
    getList();
    // getListb()
    // getListvip()
    // getListcard()
  });
</script>
